/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jeff.springWebTestNG.concurrent;

import java.util.concurrent.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author zhou.zhefu
 */
public class ExecutorEmulator {
    private static final long startTime = System.nanoTime();
    private final ExecutorService exec1 = Executors.newFixedThreadPool(3);
    private final ScheduledExecutorService exec2 = Executors.newScheduledThreadPool(3);
    
    public void startBasicExecutorTasks() {
        for (int i = 1; i <= 7; i++) {
            exec1.execute(new Job(i));
        }
        try {
            exec1.awaitTermination(3000, TimeUnit.MILLISECONDS);
            System.out.println("All jobs DONE.");
        } catch (InterruptedException ex) {
            System.out.println("Terminate executor due to time-out");
            Logger.getLogger(ExecutorEmulator.class.getName()).log(Level.WARNING, null, ex);
        }
    }
    
    private class Job implements Runnable {
        int id;

        public Job(int id) {
            this.id = id;
        }
        
        @Override
        public void run() {
            try {
                //TODO job processing...
                Thread.sleep(1);
                System.out.println(this + " is DONE at Time: " + (System.nanoTime() - startTime));
            } catch (InterruptedException ex) {
                Logger.getLogger(Job.class.getName()).log(Level.SEVERE, null, ex);
            }
            
        }

        @Override
        public String toString() {
            return "Job[" + id + "]";
        }
    }
    
    public void startScheduledExecutor() {
        try {
            Future future = exec2.scheduleWithFixedDelay(new Job(1), 0, 10, TimeUnit.MILLISECONDS);
            exec2.awaitTermination(1000, TimeUnit.MILLISECONDS);
        } catch (InterruptedException ex) {
            Logger.getLogger(ExecutorEmulator.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
